package edu.tyut.game.logic

import edu.tyut.game.GameApplication
import edu.tyut.game.logic.Repository.fire
import edu.tyut.game.logic.dao.GameDB
import edu.tyut.game.logic.dao.GameDB.existUser
import edu.tyut.game.logic.dao.GameDB.registerDB
import edu.tyut.game.logic.model.Game
import edu.tyut.game.logic.model.User
import edu.tyut.game.logic.network.GameNetWork
import edu.tyut.game.utils.LogUtils
import okhttp3.MultipartBody

object UserRepository {

    private const val tag = "UserRepository"

    /**
     * 登录，先本地数据库查询，然后网络查询
     */
    fun login(user: User) = fire {
        // 先走本地数据库
        val userDB = existUser(user)
        LogUtils.d(tag, userDB.toString())
        if (userDB != null){
            Result.success(userDB)
        }else{
            // 再走网络
            val res = GameNetWork.login(user)
            if (res.status == "ok"){
                // 保存在数据库
                registerDB(res.data!!)
                Result.success(res.data)
            }else{
                Result.failure(Exception("登录失败：${res.msg}"))
            }
        }
    }

    /**
     * 获取找回密码的用户
     */
    fun getUser(username: String) = fire {
        LogUtils.d(tag, "getUser")
        val res = GameNetWork.getUser(username)
        if (res.status == "ok"){
            LogUtils.d(tag, res.data.toString())
            Result.success(res.data)
        }else{
            Result.failure(Exception("获取用户失败: ${res.msg}"))
        }
    }

    /**
     * 用户是否存在走网络
     */
    fun isExistsUserWeb(user: User) = fire {
        val res = GameNetWork.isExistUser(mapOf("username" to user.username))
        if (res.status == "ok"){
            Result.success(res.data)
        }else{
            Result.failure(RuntimeException("失败原因：${res.msg}"))
        }
    }

    fun updatePassword(user: User) = fire {
        val res = GameNetWork.updatePassword(user)
        if (res.status == "ok"){
            LogUtils.d(tag, "密码是否修改成功: ${res.data}")
            GameDB.updatePassword(user)
            Result.success(res.data)
        }else{
            LogUtils.e(tag, "密码修改失败")
            Result.failure(Exception("密码修改失败"))
        }
    }



    /**
     * 注册是一定要走网络的
     */
    fun registerWeb(user: User) = fire {
        val registerResult = GameNetWork.register(user)
        if (registerResult.status == "ok"){
            LogUtils.d(tag, "存入数据库")
            registerDB(user)
            Result.success(registerResult.msg)
        }else{
            Result.failure(RuntimeException("失败原因：${registerResult.msg}"))
        }
    }

    fun updateHeadIcon(files: List<MultipartBody.Part>) = fire {
        val res = GameNetWork.updateHeadIcon(files)
        if (res.status == "ok"){
            LogUtils.d(tag, "头像修改成功, 头像地址为: ${res.msg}")
            GameDB.updateHeadIcon(GameApplication.loginUser?.id ?: 1, res.msg)
            Result.success(res.data)
        }else{
            LogUtils.d(tag, "头像修改失败")
            Result.failure(Exception("头像修改失败"))
        }
    }
}